/**
 * @File   : CreateProject.js
 * @Author : xue.xiaoBing
 * @Date   : 2020/12/8
 * @Desc   : 创建项目
 **/

import moment from "moment";
import {connect} from "react-redux";
import React, {Component, Fragment} from "react";
import {createProject, addProjectMember} from "src/api/request";
import {Row, Col, Steps, Button, Form, Input, Space, DatePicker, Select} from "antd";
import {
  LeftSquareOutlined,
  RightSquareOutlined,
  UploadOutlined,
  UserOutlined,
  PlusOutlined,
  MinusCircleOutlined,
  MenuOutlined,
  HomeOutlined,
  GlobalOutlined,
  StarOutlined,
  OrderedListOutlined
} from '@ant-design/icons';

import {openNotification} from "src/utils/Notification"
import UnitTitle from "src/components/Title/UnitTitle/UnitTitle";

import "./CreateProject.sass";


const {Step} = Steps;
const {Option} = Select;
const {RangePicker} = DatePicker;


class CreateProject extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 0,
      formData: {
        teamInfo: [],
        projectInfo: {
          "projectName": null,
          "projectCompany": null,
          "OperateDate": null,
          "projectAddress": null,
          "startDate": null,
          "endData": null,
          "sorties": null,
          "flyTime": null,
          "weather": null,
          "description": null
        },
        equipmentInfo: {
          "uav": null,
          "camera": null
        },
      }
    }
  }

  // 下一步
  next() {
    const current = this.state.current + 1;
    this.setState({current});
  }

  // 上一步
  prev() {
    const current = this.state.current - 1;
    this.setState({current});
  }

  // 修改step
  onChangeStep = current => {
    this.setState({current});
  };

  // 监听项目信息表单
  onFinishProjectInfo = (data) => {
    this.setState({
      ...this.state,
      formData: {
        ...this.state.formData,
        projectInfo: {
          "projectName": data[0].value,
          "projectCompany": data[1].value,
          "OperateDate": moment(data[2].value).format('YYYY-MM-DD hh:mm:ss'),
          "projectAddress": data[3].value,
          "startDate": data[4].value ? moment(data[4].value[0]).format('YYYY-MM-DD hh:mm:ss') : null,
          "endDate": data[4].value ? moment(data[4].value[1]).format('YYYY-MM-DD hh:mm:ss') : null,
          "sorties": data[5].value,
          "flyTime": data[6].value,
          "weather": data[7].value,
          "description": data[8].value
        }
      }
    });
  };

  // 监听设备信息表单
  onFinishEquipmentInfo = (data) => {
    this.setState({
      ...this.state,
      formData: {
        ...this.state.formData,
        equipmentInfo: {
          "uav": data[0].value,
          "camera": data[1].value,
        }
      }
    });
  };

  // 监听团队信息表单
  onFinishTeamInfo = (data) => {
    let temp_list = [];

    if (data.length >= 3) {
      data.splice(2, 1)
    }

    for (let i = 0; i < data.length / 2; i++) {
      temp_list.push({"fullName": data[i * 2].value, "role": data[i * 2 + 1].value})
    }

    this.setState({
      ...this.state,
      formData: {
        ...this.state.formData,
        teamInfo: temp_list
      }
    });
  };

  onSubmit = () => {
    // project项目数据
    const projectData = {
      "name": this.state.formData.projectInfo.projectName,
      "company": this.state.formData.projectInfo.projectCompany,
      "weather": this.state.formData.projectInfo.weather,
      "sorties": this.state.formData.projectInfo.sorties,
      "description": this.state.formData.projectInfo.description,
      "end_date": this.state.formData.projectInfo.endDate,
      "start_date": this.state.formData.projectInfo.startDate,
      "fly_time": this.state.formData.projectInfo.flyTime,
      "full_name": "薛晓冰",
      "location": this.state.formData.projectInfo.projectAddress,
      "operation_date": this.state.formData.projectInfo.OperateDate,
      "uav_name": this.state.formData.equipmentInfo.uav,
      "camera_name": this.state.formData.equipmentInfo.camera,
    };


    this.props.createProject(projectData)
      .then(ret => {
          // 上传团队信息
          for (let i of this.state.formData.teamInfo) {
            this.props.addProjectMember(
              {
                project_id: ret.data.id,
                role: i.role,
                full_name: i.fullName
              }
            )
          }
        }
      )
      .then(() => {
          openNotification("创建成功", '新项目创建成功...', 2);
          window.location.reload();
        }
      )
  };


  render() {
    const {current} = this.state;
    const steps = [
      <Form
        name='project_info'
        className='project-info-form'
        component={false}
        onFieldsChange={(_, allFilelds) => {
          this.onFinishProjectInfo(allFilelds)
        }}
      >
        <Space className={'space'} size={10} direction="vertical">
          <Row align={'space-around'} gutter={[18, 0]}>
            <Col span={6}>
              <Form.Item label={'项目名称'} name="projectName" rules={[{required: true, message: '输入项目名称!'}]}>
                <Input
                  prefix={<MenuOutlined className="site-form-item-icon"/>}
                  placeholder="输入项目名称"/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={'项目公司'} name="projectCompany" rules={[{required: true, message: '输入所属公司!'}]}>
                <Input prefix={<HomeOutlined className="site-form-item-icon"/>}
                       placeholder="输入所属公司"/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={'运营时间'} name="OperateDate" rules={[{required: true, message: '输入运营时间!'}]}>
                <DatePicker className={'all-width'}/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={'项目地址'} name="projectAddress" rules={[{required: true, message: '输入项目地址!'}]}>
                <Input prefix={<GlobalOutlined className="site-form-item-icon"/>} placeholder="输入项目地址"/>
              </Form.Item>
            </Col>
          </Row>
          <Row align={'space-around'} gutter={[18, 0]}>
            <Col span={12}>
              <Form.Item label={'起止时间'} name="startDate" rules={[{required: true, message: '输入起止时间!'}]}>
                <RangePicker className={'all-width'}/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={'飞行架次'} name="sorties" rules={[{required: true, message: '输入飞行架次!'}]}>
                <Input prefix={<OrderedListOutlined className="site-form-item-icon"/>} placeholder="输入飞行架次"/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={'飞行时长'} name="flyTime" rules={[{required: true, message: '输入飞行时间!'}]}>
                <Input prefix={<OrderedListOutlined className="site-form-item-icon"/>} placeholder="输入飞行时间"/>
              </Form.Item>
            </Col>
          </Row>
          <Row align={'space-around'} gutter={[18, 0]}>
            <Col span={24}>
              <Form.Item label={'天气情况'} name="weather" rules={[{required: true, message: '输入天气情况!'}]}>
                <Input prefix={<StarOutlined className="site-form-item-icon"/>} placeholder="输入天气情况"/>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item label="项目简介" name="description"
                         rules={[{required: true, message: 'Please input your projectName!'}]}>
                <Input.TextArea className={'input-textarea'} placeholder="输入项目信息"/>
              </Form.Item>
            </Col>
          </Row>
        </Space>
      </Form>,
      <Form
        name='equipment_info'
        className='equipment-info-form'
        component={false}
        onFieldsChange={(_, allFilelds) => {
          this.onFinishEquipmentInfo(allFilelds)
        }}
      >
        <Row align={'space-around'} gutter={[18, 0]}>
          <Col span={10}>
            <Form.Item label={'无人机型号'} name="uav" rules={[{required: true, message: '选择无人机型号!'}]}>
              <Select>
                <Option value="M300RTK">M300RTK</Option>
                <Option value="M210RTK">M210RTK</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item label={'镜头型号'} name="camera" rules={[{required: true, message: '选择镜头型号!'}]}>
              <Select>
                <Option value="XT2">XT2</Option>
                <Option value="H20T">H20T</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
      </Form>,
      <Form
        name='team_info'
        className='team-info-form'
        component={false}
        onFieldsChange={(_, allFilelds) => {
          this.onFinishTeamInfo(allFilelds)
        }}
      >
        <Row align={'space-around'} gutter={[18, 0]}>
          <Col span={10}>
            <Form.Item label={'用户'} name={'fullName-0'} rules={[{required: true, message: '请输入用户全名!'}]}>
              <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="请输入用户全名!"/>
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item label={'角色'} name="role-0" rules={[{required: true, message: '选择成员角色!'}]}>
              <Select>
                <Option value="负责人">负责人</Option>
                <Option value="前端">前端</Option>
                <Option value="后端">后端</Option>
                <Option value="算法">算法</Option>
                <Option value="飞手">飞手</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={1}>
          </Col>
        </Row>
        <Form.List name={'item'}>
          {(fields, {add, remove}) => {
            return (
              <Fragment>
                {fields.map((field, index) => (
                  <Row key={index.toString()} justify={'space-around'} align={'top'} gutter={[18, 0]}>
                    <Col span={10}>
                      <Form.Item
                        label={'用户'}
                        name={[field.name, 'fullName-' + (index + 1)]}
                        filedkey={[field.fieldKey, 'fullName-' + (index + 1)]}
                        rules={[{required: true, message: '请输入用户全名!'}]}
                      >
                        <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="请输入用户全名!"/>
                      </Form.Item>
                    </Col>
                    <Col span={10}>
                      <Form.Item
                        label={'角色'}
                        name={[field.name, 'role-' + (index + 1)]}
                        filedkey={[field.fieldKey, 'role-' + (index + 1)]}
                        rules={[{required: true, message: '选择成员角色!'}]}
                      >
                        <Select>
                          <Option value="负责人">负责人</Option>
                          <Option value="前端">前端</Option>
                          <Option value="后端">后端</Option>
                          <Option value="算法">算法</Option>
                          <Option value="飞手">飞手</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={1}>
                      <MinusCircleOutlined onClick={() => remove(field.name)}/>
                    </Col>
                  </Row>
                ))}
                <Row className={'add-user'}>
                  <Col span={20} offset={2}>
                    <Form.Item className={'item'} style={{width: '100%', textAlign: 'center'}}>
                      <Button
                        type="dashed"
                        onClick={() => {
                          add()
                        }}
                        style={{width: '40%', textAlign: 'center'}}
                      >
                        <PlusOutlined/> 添加用户
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Fragment>
            );
          }}
        </Form.List>
      </Form>
    ];
    return (
      <div className={'create-project'}>
        <UnitTitle mainTitle={'创建项目'} subTitle={'步骤'}/>
        <Steps className={'create-project-steps-list'} type={'navigation'} current={current}
               size='small' onChange={this.onChangeStep}>
          <Step title='项目信息'/>
          <Step title='设备信息'/>
          <Step title='团队信息'/>
        </Steps>
        <div className="create-project-steps-content">
          {steps[current]}
        </div>
        <div className="steps-action">
          {current < steps.length - 1 && (
            <Button className={'btn-next'} type="primary" icon={<RightSquareOutlined/>} onClick={() => this.next()}>
              下一步
            </Button>
          )}
          {current === steps.length - 1 && (
            <Button className={'btn-submit'} icon={<UploadOutlined/>} onClick={this.onSubmit}>
              提&nbsp;&nbsp;交
            </Button>
          )}
          {current > 0 && (
            <Button className={'btn-previous'} icon={<LeftSquareOutlined/>} type="primary" onClick={() => this.prev()}>
              上一步
            </Button>
          )}
        </div>
      </div>
    )
  }
}


export default connect(null, {createProject, addProjectMember})(CreateProject)